package com.byit.Test.wait;

/**
 * @ClassName ThreadWait
 * @Description wait, 与notify是针对已经获取了Obj锁进行操作
 * @Author lxp
 * @Date 2018/10/8 0008
 **/
public class ThreadWait implements Runnable {

    private String name;
    private Object prev;
    private Object self;

    ThreadWait(String name, Object prev, Object self) {
        this.name = name;
        this.prev = prev;
        this.self = self;
    }

    @Override
    public void run() {
        int count = 10;
        while (count > 0) {
            synchronized (prev) {
                synchronized (self) {
                    System.out.println(name);
                    count--;
                    /**
                     * self:abc
                     * 唤醒等待线程,synchronized(){}语句块执行结束，自动释放锁后，
                     * JVM会在wait()对象锁的线程中随机选取一线程，赋予其对象锁，唤醒线程，继续执行
                     */
                    self.notify();
                   /* String t = Thread.currentThread().getName();
                    System.out.println("=====" + "当前线程: " + t + "=====");*/
                }
                try {
                    /**
                     * prev:cab
                     * 主动释放锁,同时本线程休眠;
                     * 直到有其它线程调用notify()唤醒该线程,才能继续获取该对象
                     */
                    prev.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
